package com.jstyle.beatecg.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.jstyle.beatecg.R;
import com.jstyle.beatecg.activity.ActivitySportActivity;
import com.jstyle.beatecg.activity.HistoryActivity;
import com.jstyle.beatecg.activity.SportTypeActivity;
import com.jstyle.beatecg.adapter.SportHistoryAdapter;
import com.jstyle.beatecg.base.BaseFragment;
import com.jstyle.beatecg.ble.BleService;
import com.jstyle.beatecg.daoManager.PathRecordDaoManager;
import com.jstyle.beatecg.model.BleData;
import com.jstyle.beatecg.model.PathRecord;
import com.jstyle.beatecg.util.GlobalConast;
import com.jstyle.beatecg.util.RxBus;
import com.jstyle.beatecg.util.ScreenUtils;

import java.util.Calendar;
import java.util.List;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static android.content.Context.LOCATION_SERVICE;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link SportFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SportFragment extends BaseFragment implements SportHistoryAdapter.onItemClickListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.ll_title)
    LinearLayout llTitle;
    @BindView(R.id.bt_sport_type)
    Button btSportType;
    @BindView(R.id.iv_sport_type)
    ImageView ivSportType;
    @BindView(R.id.bt_start_sport)
    Button btStartSport;
    Unbinder unbinder;
    @BindView(R.id.bt_data_day_preDay)
    ImageView btDataDayPreDay;
    @BindView(R.id.bt_data_day_date)
    Button btDataDayDate;
    @BindView(R.id.bt_data_day_nextDay)
    ImageView btDataDayNextDay;
    @BindView(R.id.RecyclerView_sport_history)
    RecyclerView RecyclerViewSportHistory;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private List<PathRecord> pathRecords;
    private SportHistoryAdapter sportHistoryAdapter;
    private Disposable subscription;
    @BindArray(R.array.sport_type_array)
    String[]arraySport;
    private int year;

    public SportFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *

     * @return A new instance of fragment SportFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static SportFragment newInstance() {
        SportFragment fragment = new SportFragment();
        Bundle args = new Bundle();
      //  args.putString(ARG_PARAM1, param1);
     //   args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_sport, container, false);
        unbinder = ButterKnife.bind(this, view);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            ScreenUtils.setStatusBarColor(llTitle, android.R.color.transparent);
        }
        initView();
        return view;
    }

    private void initView() {
        Calendar calendar=Calendar.getInstance();
        year=calendar.get(Calendar.YEAR);
       updateYearView();
        updateSportType(1);
        subscription = RxBus.getInstance().toObservable(BleData.class).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<BleData>() {
            @Override
            public void accept(BleData data) throws Exception {
                String action = data.getAction();
                if(GlobalConast.KEY_SportType.equals(action)){
                    int position= (int) data.getData();
                    updateSportType(position);
                }else if("up_history".equals(action)){
                    updateYearView();
                }
            }


        });
        LinearLayoutManager manager=new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        DividerItemDecoration dividerItemDecoration=new DividerItemDecoration(getActivity(),DividerItemDecoration.VERTICAL);
        dividerItemDecoration.setDrawable(getResources().getDrawable(R.drawable.sport_divider));
        RecyclerViewSportHistory.addItemDecoration(dividerItemDecoration);
        RecyclerViewSportHistory.setLayoutManager(manager);
    }
    private void updateSportType(int position) {
        int id = getResources().getIdentifier("sport_home_" + position, "drawable", getActivity().getPackageName());
        Drawable drawable= getResources().getDrawable(id);
        ivSportType.setImageDrawable(drawable);
        btSportType.setText(arraySport[position]);
    }
    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onResume() {
        super.onResume();


    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        unsubscribe(subscription);
    }

    @OnClick({R.id.bt_sport_type, R.id.bt_data_day_nextDay,R.id.bt_start_sport,R.id.bt_data_day_preDay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_data_day_preDay:
                year--;
               updateYearView();
                break;
            case R.id.bt_data_day_nextDay:
                year++;
               updateYearView();
                break;
            case R.id.bt_sport_type:
                startActivity(SportTypeActivity.class);
                break;
            case R.id.bt_start_sport:
                if(checkGps()){
                    Intent intent =new Intent(getActivity(),ActivitySportActivity.class);
                    intent.putExtra("type",btSportType.getText().toString().trim());
                    startActivity(intent);

                }else{
                    showEnableGpsDialog();
                }

                break;
        }
    }

    private void updateYearView(){
        btDataDayDate.setText(String.valueOf(year));
        Calendar calendar=Calendar.getInstance();
        int yearNow=calendar.get(Calendar.YEAR);
        btDataDayNextDay.setEnabled(yearNow!=year);
        final String startDate = String.valueOf(year).substring(2) + ".01.01";
        final String endDate = String.valueOf(year).substring(2) + ".12.31";
        pathRecords= PathRecordDaoManager.getPathRecord(startDate,endDate);
        sportHistoryAdapter=new SportHistoryAdapter(pathRecords,this);
        RecyclerViewSportHistory.setAdapter(sportHistoryAdapter);
    }
    private void showEnableGpsDialog() {
        AlertDialog alertDialog=new AlertDialog.Builder(getActivity())
                .setTitle(R.string.gps_off)
                .setMessage(R.string.gps_in)
                .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent=new Intent();
                        intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivity(intent);
                    }
                })
                .setNegativeButton(getString(R.string.cancel),null)
                .create();
        alertDialog.show();
    }

    private boolean checkGps(){
        LocationManager lm=(LocationManager) getActivity().getSystemService(LOCATION_SERVICE);
        return lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }
    @Override
    public void onItemClick(long id) {
        Intent intent=new Intent(getActivity(),HistoryActivity.class);
        intent.putExtra("id",id);
        startActivity(intent);
    }


    @Override
    public void onLongClick(final long id) {
        AlertDialog alertDialog=new AlertDialog.Builder(getActivity())
                .setTitle(R.string.tips)
                .setMessage(R.string.deletedata)
                .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        PathRecordDaoManager.Deletehos(id);
                        final String startDate = String.valueOf(year).substring(2) + ".01.01";
                        final String endDate = String.valueOf(year).substring(2) + ".12.31";
                        pathRecords= PathRecordDaoManager.getPathRecord(startDate,endDate);
                        sportHistoryAdapter.updata(pathRecords);
                    }
                })
                .setNegativeButton(getString(R.string.cancel),null)
                .create();
        alertDialog.show();
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
    private void unsubscribe(Disposable disposable) {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
    }
}
